package com.haiqi.config.interceptor;

import com.alibaba.fastjson.JSON;
import com.haiqi.common.utils.DesUtils;
import com.haiqi.modules.main.bean.MenuResponse;
import com.haiqi.modules.main.bean.ResponseBean;
import com.haiqi.modules.main.bean.TokenBean;
import com.haiqi.modules.main.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by hythzx on 2016/5/12.
 */


public class LoginInterceptor implements HandlerInterceptor {

    private final Logger logger = Logger.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        HttpSession session = httpServletRequest.getSession();
        //session.setMaxInactiveInterval(60);
        ResponseBean.UserBean user = (ResponseBean.UserBean) session.getAttribute("user");
        List<MenuResponse.MenusBean> menus = (List<MenuResponse.MenusBean>) session.getAttribute("menu");

        Cookie[] cookies = httpServletRequest.getCookies();
        String userCookieCode = null;
        String tokenCookieCode = null;
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("user")){
                    userCookieCode = cookie.getValue();
                    System.out.println("检测到用户cookie：" + userCookieCode);
                }
                if(cookie.getName().equals("token")){
                    tokenCookieCode = cookie.getValue();
                    System.out.println("检测到token：" + tokenCookieCode);
                }
            }
        }
        String userInfo = "";
        String tokenInfo = "";
        ResponseBean.UserBean userBean = new ResponseBean.UserBean();
        TokenBean tokenBean = new TokenBean();
        if(StringUtils.isNotEmpty(userCookieCode) && StringUtils.isNotEmpty(tokenCookieCode)){
            System.out.println("从cookie获取用户信息");
            userInfo = DesUtils.decrypt(userCookieCode, DesUtils.key);
            tokenInfo = DesUtils.decrypt(tokenCookieCode, DesUtils.key);
            System.out.println("自动登录的用户信息："+userInfo);
            userBean = JSON.parseObject(userInfo, ResponseBean.UserBean.class);
            tokenBean = JSON.parseObject(tokenInfo, TokenBean.class);
        }

        if(user == null){
            System.out.println("当前没有用户登录信息");
            if(org.apache.commons.lang.StringUtils.isEmpty(userCookieCode) || StringUtils.isEmpty(tokenCookieCode)){  //没有cookie
                System.out.println("没有cookie");
                httpServletResponse.sendRedirect("/login");
            }else{
                logger.info("使用cookie登录");
                if(tokenBean.getToken() != null){
                    UserService userService = new UserService("cyx");
                    MenuResponse menuResponse = userService.getMenus(userBean.getId(), tokenBean.getToken());
                    if(menuResponse.isSuccess()){
                        session.setAttribute("user",userBean);
                        session.setAttribute("menu",menuResponse.getMenus());
                        return true;
                    }
                }
            }
            return false;
        }else{
            if(StringUtils.isNotEmpty(userBean.getId()) && !user.getId().equals(userBean.getId())){   //用户产生变化
                session.removeAttribute("user");
                UserService userService = new UserService("cyx");

                MenuResponse menuResponse = userService.getMenus(userBean.getId(), tokenBean.getToken());
                System.out.println("获取menu，值为：" + menuResponse);
                if(menuResponse.isSuccess()){
                    session.setAttribute("user",userBean);
                    session.setAttribute("menu",menuResponse.getMenus());
                    return true;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
